package com.nacos.test.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.nacos.test.PersonService;
import com.nacos.test.mapper.PersonMapper;
import com.nacos.test.pojo.Person;
import com.nacos.test.utils.PagedGridResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

/**
 * 项目名称：nacos_parent
 * 类 名 称：PersonServiceImpl
 * 类 描 述：TODO
 * 创建时间：2020/5/14
 * 创 建 人：Areli
 */
@Service
public class PersonServiceImpl implements PersonService {
    @Autowired
    PersonMapper personMapper;

    // 如果其他bean调用这个方法,在其他bean中声明事务,那就用事务.如果其他bean没有声明事务,那就不用事务.
    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public Person queryPersonByPersonId(Integer id) {
        Example example = new Example(Person.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("id",id);
        return personMapper.selectOneByExample(example);
    }

    @Override
    public PagedGridResult queryPersonLikeUsername(String username, Integer page, Integer pageSize) {
        Example example = new Example(Person.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("username","%"+username+"%");
        PageHelper.startPage(page,pageSize);
        List<Person> list = personMapper.selectByExample(example);

        return setterPageGrid(list,page);
    }

    @Override
    public Person savePerson(Person person) {
        personMapper.insertSelective(person);
        return personMapper.selectOne(person);
    }

    @Override
    public Person editPerson(Person person) {
        Example example = new Example(Person.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("id",person.getId());
        personMapper.updateByExample(person,example);
        return personMapper.selectOne(person);
    }

    @Override
    public void deletePersonByPersonId(Integer id) {
        Example example = new Example(Person.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("id",id);
        personMapper.deleteByExample(example);
    }

    public PagedGridResult setterPageGrid(List<?> list,Integer page){
        PageInfo<?> pageInfo = new PageInfo<>(list);
        PagedGridResult grid = new PagedGridResult();
        grid.setPage(page);
        grid.setRows(list);
        grid.setTotal(pageInfo.getPages());
        grid.setRecords(pageInfo.getTotal());
        return grid;
    }
}
